package com.zhaojiadi.spring.bean.definition;

import com.zhaojiadi.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 实例化Bean
 * 注解BeanDefinition 示例
 */
// 3.通过@Import来进行导入
    @Import(AnnotationBeanDefinitionDemo.Config.class)
public class AnnotationBeanDefinitionDemo {

    public static void main(String[] args) {
        //创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 Configuration Class(配置类)
        applicationContext.register(AnnotationBeanDefinitionDemo.class);

        //通过 BeanDefinition 注册 API 实现
        // 1. 命名Bean的注册方式
        registerUserBeanDefinition(applicationContext,"mercyblitz-user");
        //2. 非命名方法的注册方法
        registerUserBeanDefinition(applicationContext);

        //启动Spring 应用上下文
        applicationContext.refresh();
        //按照类型依赖查找
        System.out.println("Config 类型的所有Bean"+applicationContext.getBeansOfType(Config.class));
        System.out.println("User类型的所有Bean"+applicationContext.getBeansOfType(User.class));

        //显示的关闭Spring应用上下文
        applicationContext.close();
    }

    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry) {
        registerUserBeanDefinition(registry, null);
    }

    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry,String beanName){
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id",1).addPropertyValue("name","小马哥");
        //判断如果BeanName参数存在时
        if(StringUtils.hasText(beanName)){
            registry.registerBeanDefinition(beanName,beanDefinitionBuilder.getBeanDefinition());
        }else{
            // 非命名 Bean注册方法
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(),registry);
        }
    }

    //2.通过Component方式
    @Component
    public class Config{
        //1.通过@Bean方式定义
        @Bean(name = {"user","xiaomage-user"})
        public User user(){
            User user = new User();
            user.setId(1L);
            user.setName("xiaomage");
            return user;
        }

    }
}
